package com.example.mcp.controller;

import com.example.mcp.service.McpChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * AI MCP控制器 - 让AI能够调用MCP客户端功能
 */
@RestController
@RequestMapping("/api/ai-mcp")
@CrossOrigin(origins = "*")
public class AiMcpController {

    private static final Logger logger = LoggerFactory.getLogger(AiMcpController.class);

    @Autowired
    private McpChatService mcpChatService;

    /**
     * AI聊天接口 - 支持MCP客户端工具调用
     */
    @PostMapping("/chat")
    public ResponseEntity<Map<String, Object>> chat(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        String sessionId = request.getOrDefault("sessionId", "default");
        
        logger.info("🤖 AI聊天请求: {}", message);
        logger.info("🔑 会话ID: {}", sessionId);
        
        try {
            // 使用MCP聊天服务，AI可以自动调用MCP客户端工具
            String response = mcpChatService.chatSync(message, sessionId);
            
            Map<String, Object> result = Map.of(
                "success", true,
                "response", response,
                "sessionId", sessionId,
                "timestamp", System.currentTimeMillis()
            );
            
            logger.info("✅ AI聊天响应成功");
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("❌ AI聊天失败", e);
            
            Map<String, Object> result = Map.of(
                "success", false,
                "error", e.getMessage(),
                "sessionId", sessionId,
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取AI可用的MCP工具列表
     */
    @GetMapping("/tools")
    public ResponseEntity<Map<String, Object>> getAvailableTools() {
        logger.info("🔧 获取AI可用MCP工具列表");
        
        Map<String, Object> tools = Map.of(
            "mcpClientTools", Map.of(
                "getAllConversations", "获取所有聊天记录列表",
                "getConversationById", "根据ID获取特定聊天记录",
                "getMessagesByConversationId", "获取指定会话的消息列表",
                "sendMessage", "向指定会话发送消息",
                "pingMcpServer", "测试MCP服务器连接状态",
                "checkMcpHealth", "检查MCP客户端健康状态"
            ),
            "description", "AI可以通过这些工具与MCP服务器进行交互，获取和发送消息",
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(tools);
    }

    /**
     * 测试AI工具调用
     */
    @PostMapping("/test-tools")
    public ResponseEntity<Map<String, Object>> testTools(@RequestBody Map<String, String> request) {
        String testMessage = request.getOrDefault("message", "请帮我获取所有聊天记录，然后发送一条测试消息");
        
        logger.info("🧪 测试AI工具调用: {}", testMessage);
        
        try {
            // 使用 "test" 作为测试会话的 sessionId
            String response = mcpChatService.chatSync(testMessage, "test");
            
            Map<String, Object> result = Map.of(
                "success", true,
                "testMessage", testMessage,
                "aiResponse", response,
                "description", "AI已成功调用MCP客户端工具",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("❌ AI工具测试失败", e);
            
            Map<String, Object> result = Map.of(
                "success", false,
                "error", e.getMessage(),
                "testMessage", testMessage,
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(result);
        }
    }
}
